package com.course.finalproject.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.course.finalproject.Constants;
import com.course.finalproject.MyApplication;
import com.course.finalproject.R;
import com.course.finalproject.Utility;
import com.course.finalproject.adapter.BatteryLogArrayAdapter;
import com.course.finalproject.model.BatteryLog;

/**
 * Class that represent the battery log activity.
 * @author	Mariano Bessone <mariano.bessone @ tallertechnologies.com>
 * @since	2012-09-18
 */
public class BatteryActivity extends ListActivity {

	/** Adapter. */
	private BatteryLogArrayAdapter batteryAdapter;

	/** Local broadcast receiver for update the list of battery logs. */
	private BroadcastReceiver batteryNewLogReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();
			BatteryLog log = bundle.getParcelable(Constants.BATTERY_LOG_PARCEL_KEY);
			batteryAdapter.add(log);
    	}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.d(Constants.LOG_TAG, "BatteryActivity.onCreate()");
		// Super call.
		super.onCreate(savedInstanceState);
		// Create and set list adapter.
		batteryAdapter = new BatteryLogArrayAdapter( this, MyApplication.getInstance().getBatteryManager().getBatteryLogs() );
		setListAdapter(batteryAdapter);
		// Register to receive a new battery log to notify to the adapter.
		LocalBroadcastManager.getInstance(this).registerReceiver(batteryNewLogReceiver, new IntentFilter(Constants.NEW_LOG_BATTERY_MSG));
	}
	
	@Override
	protected void onDestroy() {
		// Unregister to do not receive a new battery log from now.
		LocalBroadcastManager.getInstance(this).unregisterReceiver(batteryNewLogReceiver);
		// Super call.
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.battery_log_list_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection.
	    switch (item.getItemId()) {
	        case R.id.battery_log_menu_clean:
	        	// Clear global battery log list and the local list adapter.
	        	MyApplication.getInstance().getBatteryManager().clearBatteryLog();
	        	batteryAdapter.clear();
	        	// Finished.
	            return true;
	        case R.id.battery_log_menu_send:
	        	// Launch the android contacts activity to pick the contacts.
	        	pickContactForEmail();
	        	// Finished.
	        	return true;
	        default:
	        	// Super handler.
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	/**
	 * Launch the android contacts intent to pick the contacts for sending an email.
	 * It starts the activity expecting a result.
	 */
	private void pickContactForEmail() {
		Intent pickContactIntent = new Intent(Intent.ACTION_PICK);
	    pickContactIntent.setType(ContactsContract.Contacts.CONTENT_TYPE);
	    startActivityForResult(pickContactIntent, Constants.PICK_CONTACT_REQUEST_CODE);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    // Check which request we're responding to
	    if (requestCode == Constants.PICK_CONTACT_REQUEST_CODE) {
	        // Make sure the request was successful
	        if (resultCode == RESULT_OK) {
	            Uri contactData = data.getData();
	            Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
	            if ( cursor.getCount() > 0 ) {
	            	cursor.moveToFirst();
	            	String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
	            	Cursor emailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
	            	if ( emailCursor.getCount() > 0 ) {
	            		List<String> emails = new ArrayList<String>();
	            		while ( emailCursor.moveToNext() ) {
		            		String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
		            		if ( !emails.contains(email) )
		            			emails.add(email);
	            		}
	            		// Send an email to all e-mail adresses of the picked contact.
	            		sendEmail(emails);
	            	} else {
		            	Utility.toast(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) + " does not have an e-mail attached.");
		            }
	            	// Close the email cursor.
	            	emailCursor.close();
	            }
	            // Close the contacts cursor.
	            cursor.close();
	        }
	    }
	}
	
	private void sendEmail(List<String> recipients) {
		Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
		emailIntent.setType("plain/text");
		// Set email recipients and subject.
		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients.toArray(new String[0]));
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Battery events");
		// Set email body.
		String body = "";
		if ( MyApplication.getInstance().getBatteryManager().getBatteryLogs().isEmpty() ) {
			body = "There are not battery events";
		} else {
			for (BatteryLog log : MyApplication.getInstance().getBatteryManager().getBatteryLogs()) {
				body += log.toString() + "\n";
			}
		}
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
		// Launch email activity.
		startActivity(Intent.createChooser(emailIntent, "Choose an email client :"));
	}
}
